
/**
 * @file in_flash.c
 * @author Linquan  
 * @brief   
 *          when erase ,erase one page,
 *          one page = IN_PAGE_SIZE(2K),
 *          the nor flash has IN_PAGES_PER_BLIOCK(128) pages
 *          flash start address from IN_FLASH_START(0x08000000)
 * @version 0.2
 * @date 2024-02-26
 * 
 * @copyright Copyright (c) 2024
 * 
 */


#include "in_flash.h"
#include "c_mem.h"
#include "stdio.h"
#include "string.h"

#define IN_FLASH_START           0x08000000    // flash起始地址
#define IN_PAGE_SIZE             (1024*2)       // 页大小
#define IN_PAGES_PER_BLIOCK      128        // 页数

#define IN_FLASH_SIZE            (IN_PAGES_PER_BLIOCK*IN_PAGE_SIZE)

uint8_t in_flash_arry[IN_FLASH_SIZE]= {0};


void in_flash_print(uint32_t start_addr, uint32_t end_addr);


void in_flash_init()
{
    memset(in_flash_arry, 0XFF, IN_FLASH_SIZE);
}

/**
 * @brief 
 * 
 * @param addr 
 * @return uint8_t : err return 1  rigth return 0
 */
uint8_t in_flash_erase(uint32_t addr)
{
    uint32_t sec_addr = 0;

    addr -= IN_FLASH_START;  

    if(addr >= IN_FLASH_SIZE)
    {
        printf("error in flash erase addr is too large\n");
        return 1;
    }

    sec_addr = (addr/(IN_PAGE_SIZE))*(IN_PAGE_SIZE);
   
   memset(&in_flash_arry[sec_addr], 0XFF, IN_PAGE_SIZE);
}

/**
 * @brief 
 * 
 * @param addr 
 * @param buff 
 * @param len 
 * @return uint8_t : err return 1  rigth return 0
 */
uint8_t in_flash_read(uint32_t addr, uint8_t* buff, uint16_t len)
{
    addr -= IN_FLASH_START;

    if(addr >= IN_FLASH_SIZE)
    {
        printf("error in flash read addr is too large\n");
        return 1;
    }

     c_memcpy(buff, &in_flash_arry[addr],  len);
     return 0;
}

/**
 * @brief 
 * 
 * @param addr 
 * @param buff 
 * @param len 
 * @return uint8_t :err return 1  rigth return 0
 */
uint8_t in_flash_write(uint32_t addr, uint8_t* buff, uint16_t len)
{
    addr -= IN_FLASH_START;

    if(addr >= IN_FLASH_SIZE)
    {
        printf("error in flash write addr is too large\n");
        return 1;
    }
    c_memcpy(&in_flash_arry[addr], buff, len);

    return 0;
}



void in_flash_print(uint32_t start_addr, uint32_t end_addr)
{
    start_addr -= IN_FLASH_START;
    end_addr   -= IN_FLASH_START;

    if(start_addr > end_addr) 
    {
        printf("error: start_addr > end_addr\n");
        return ;
    }

    for(int offset = start_addr,i = 0; offset < end_addr; offset++)
    {
         printf("%#x ",in_flash_arry[offset]);
         i++;
         if(i == 8)
         {
            printf("\n");
         }
    }
   
}




